
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load="getList"
        @search-change="searchChange"
        @search-reset="searchReset"
        @refresh-change="refreshChange"
        @selection-change="selectionChange"
      >
        <template
          slot="menu"
          slot-scope="{row,size}"
        >
          <el-button size="small"   @click="preivew(row)">各线路占比</el-button>
          <el-button size="mini" type="primary" v-if="row.dataSource==2"  @click="handleEdit(row)">编辑</el-button>
        </template>
        <template
          slot="calcTime"
          slot-scope="scope"
        >
          {{scope.row.beginTime}} ~ {{scope.row.endTime}}
        </template>
        <template slot="menuRight">
          <el-button
            type="primary"
            size="small"
            @click="handleoneSidedAdd"
          >单边销售</el-button>
          <el-button
            type="primary"
            size="small"
            @click="dialogVisible = true"
          >系统自动计算/按月</el-button>
          <el-button
            type="primary"
            size="small"
            @click="dialogVisible2 = true"
          >系统自动计算/按天</el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleStart"
          >设为当前使用</el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleStop"
          >暂停使用</el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleAdd"
          >添加</el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleDelete"
          >删除</el-button>
          <el-button
            size="small"
            v-if="permissionList.export"
            @click="exportClick"
          >导出</el-button>
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog
      title="系统自动计算/按月"
      width="500px"
      :visible.sync="dialogVisible"
    >
      <avue-form
        ref="form"
        v-model="autoCleanForm"
        :option="option"
        @submit="submit"
      >
      </avue-form>
    </el-dialog>
    <el-dialog
      title="系统自动计算/按天"
      width="500px"
      :visible.sync="dialogVisible2"
    >
      <avue-form
        ref="form"
        v-model="autoCleanForm2"
        :option="option2"
        @submit="submitDay"
      >
      </avue-form>
    </el-dialog>
    <el-dialog
      title="各线路占比"
      width="1000px"
      :visible.sync="dialogPreviewVisible"
    >
      <avue-crud
        v-if="dialogPreviewVisible"
        ref="crud"
        :data="tablePreviewData"
        :table-loading="tablePreivewLoading"
        :option="preivewTableOption"
        @on-load="getPreviewList"
      >
      </avue-crud>
    </el-dialog>
    <open-dialog title="单边销售" :DialogVisible.sync="oneSidedVisableDialog">
      <el-form label-width="60px">
        <avue-form
          ref="editForm" 
          v-model="formOneSided"
          :option="tableOptionOneSided"
        ></avue-form>
        <dynamic-crud
          title="单边销售明细"
          ref="dynamicOneSidedCrud"
          :data="formOneSided.dataOneSidedDetails"
          :option="tableOptionOneSidedDetail"
          :addNew="rowNew"
          :delRow="rowDel"
        >
        </dynamic-crud>
        <div class="bottom-menu-input">
          <el-button type="primary" @click="OneSidedEdit()">保存</el-button>
          <el-button @click="oneSidedVisableDialog = false"
            >关闭</el-button
          >
        </div>
      </el-form>
    </open-dialog>
    <open-dialog title="添加" :DialogVisible.sync="addVisableDialog">
      <el-form label-width="60px">
        <avue-form
          ref="dataForm" 
          v-model="formAdd.datas"
          :option="tableOptionAdd"
        ></avue-form>
        <dynamic-crud
          title="明细"
          ref="dynamicCrud"
          :data="formAdd.dataDetails"
          :option="tableOptionAddDetail"
          :rowAdd="rowadd"
          v-if="formAdd.datas.clearRules==2 || formAdd.datas.clearRules>=4"
        >
          <template slot-scope="scope" slot="lineCode">
            <el-select v-model="scope.row.lineCode" placeholder="请选择线路" clearable>
              <el-option
                v-for="(item,index) in lineCodes"
                :key="index"
                :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>
          </template>
        </dynamic-crud>
        <div class="bottom-menu-input">
          <el-button type="primary" @click="detailSave()">保存</el-button>
          <el-button @click="addVisableDialog = false"
            >关闭</el-button
          >
        </div>
      </el-form>
    </open-dialog>
    
    <open-dialog title="编辑" :DialogVisible.sync="editVisableDialog">
      <el-form label-width="60px">
        <avue-form
          ref="editForm" 
          v-model="formEdit.datas"
          :option="tableOptionAdd"
        ></avue-form>
        <dynamic-crud
          title="明细"
          ref="dynamicCrud"
          :data="formEdit.dataDetails"
          :option="tableOptionAddDetail"
          :rowAdd="rowadd"
          v-if="formEdit.datas.clearRules==2 || formEdit.datas.clearRules>=4"
        >
          <template slot-scope="scope" slot="lineCode">
            <el-select v-model="scope.row.lineCode" placeholder="请选择线路" clearable>
              <el-option
                v-for="(item,index) in lineCodes"
                :key="index"
                :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>
          </template>
        </dynamic-crud>
        <div class="bottom-menu-input">
          <el-button type="primary" @click="detailEdit()">保存</el-button>
          <el-button @click="editVisableDialog = false"
            >关闭</el-button
          >
        </div>
      </el-form>
    </open-dialog>
  </div>
</template>

<script>
import { fetchListB, previewLine, autoComputeMonth,autoComputeDay, listoperators, delObj, dataExport, updateUsedStateToStop, updateUsedStateToUse,getObj,addObj,putObj,getLines,getOneSidedLines,updateOneSidedSales } from '@/api/rca/swckclearrules'
import { tableOption, preivewTableOption,tableOptionAdd,tableOptionAddDetail,tableOptionOneSided,tableOptionOneSidedDetail } from '@/const/crud/rca/swckclearrules2'
import { handleExcelResponse, getQueryString } from "@/util/util";
import { mapGetters } from 'vuex'

export default {
  name: 'swckclearrules',
  data () {
    return {
      rowNew: false,
      rowDel: false,
      searchForm: {
        usedState: '1' //默认查启用
      },
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,

      current: null,
      tablePreviewData: [],
      tablePreivewLoading: false,
      preivewTableOption: preivewTableOption,

      extraParam: {

      },
      selection: [],
      dialogVisible: false,
      dialogVisible2: false,
      autoCleanForm: {},
      autoCleanForm2: {},
      formAdd:{
        datas: {},
        dataDetails: []
      },
      formEdit:{
        datas: {},
        dataDetails: []
      },
      addVisableDialog: false,
      editVisableDialog: false,
      tableOptionAdd: tableOptionAdd,
      tableOptionAddDetail: tableOptionAddDetail,
      lineCode:{},
      lineCodes: [],

      formOneSided:{
        cleanDate: null,
        dataOneSidedDetails: []
      },
      oneSidedVisableDialog: false,
      tableOptionOneSided: tableOptionOneSided,
      tableOptionOneSidedDetail: tableOptionOneSidedDetail,
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList () {
      return {
        export: this.vaildData(this.permissions.sw_ck_clear_rules_export, false),
        delBtn: this.vaildData(this.permissions.generator_swckclearrules_del, false),
        handleStart: this.vaildData(this.permissions.sw_ck_clear_rules_use, false),
        handleStop: this.vaildData(this.permissions.sw_ck_clear_rules_stop, false),
        handleDelete: this.vaildData(this.permissions.sw_ck_clear_rules_del, false),
      };
    },
    dialogPreviewVisible: {
      get: function () {
        return !!this.current
      },
      set: function (val) {
        this.current = val ? this.current : null
      }
    },
    option () {
      return {
        submitText: '确认',
        column: [{
          label: "计算时间",
          prop: "startDate",
          type: "month",
          span: 24,
          valueFormat: 'yyyy-MM',
          labelWidth: 120,
          placeholder: "请选择计算时间",
          rules: [{
            required: true,
            message: "请选择计算时间",
            trigger: "change"
          }],
        }]
      }
    },
    option2 () {
      return {
        submitText: '确认',
        column: [{
          label: "计算开始时间",
          prop: "startDate",
          type: "date",
          span: 24,
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          labelWidth: 120,
          placeholder: "请选择计算开始时间",
          rules: [{
            required: true,
            message: "请选择计算开始时间",
            trigger: "change"
          }],
        }, {
          label: "计算结束时间",
          prop: "endDate",
          type: "date",
          span: 24,
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          labelWidth: 120,
          placeholder: "请选择计算结束时间",
          rules: [{
            required: true,
            message: "请选择计算结束时间",
            trigger: "change"
          }],
        }]
      }
    }
  },
  watch: {
    "formAdd.datas.operators"(newValue, oldValue) {
      if(!this.validatenull(newValue)){
        for(var item of this.formAdd.dataDetails){
          item.lineCode = null;
        }
        getLines(newValue).then(response => {
          this.lineCodes = response.data.data;
        }).catch(() => {
        })
      }
    },
    "formEdit.datas.operators"(newValue, oldValue) {
      if(!this.validatenull(newValue)){
        if(oldValue!=undefined){
          for(var item of this.formEdit.dataDetails){
            item.lineCode = null;
          }
        }
        getLines(newValue).then(response => {
          this.lineCodes = response.data.data;
        }).catch(() => {
        })
      }
    },
    "formOneSided.cleanDate"(newValue, oldValue) {
      if(!this.validatenull(newValue)){
        if(oldValue!=undefined){
          for(var item of this.formOneSided.dataOneSidedDetails){
            item.lineCode = null;
          }
        }
        getOneSidedLines(newValue).then(response => {
          this.formOneSided.dataOneSidedDetails = response.data.data;
          for (const item of this.formOneSided.dataOneSidedDetails) {
            item.$cellEdit = true;
          }
        }).catch(() => {
        })
        this.tableOptionOneSidedDetail.column[0].cell = false;
      }
    }
  },
  methods: {
    //单边
    handleoneSidedAdd(){
      this.formOneSided = {
        cleanDate: null,
        dataOneSidedDetails: []
      };
      this.lineCodes = [];
      this.oneSidedVisableDialog = true;
    },
    handleAdd(){
      for (var i in this.formAdd.datas) {
        this.formAdd.datas[i] = null;
      }
      this.formAdd.dataDetails = [];
      this.lineCodes = [];
      this.addVisableDialog = true;
    },
    handleEdit(row){
      this.formEdit.datas = {};
      this.formEdit.dataDetails = [];
      this.lineCodes = [];
      getObj(row.id)
        .then((response) => {
          let res = response.data.data;
          this.formEdit.datas = res.datas;
          this.formEdit.dataDetails = res.dataDetails === null ? [] : res.dataDetails;
          for (const item of this.formEdit.dataDetails) {
            item.$cellEdit = true;
          }
        })
        .then(() => {
          this.editVisableDialog = true;
        });
    },
    async detailSave(){
      let formRules = false;
      this.$refs.dataForm.validate(vaild=>{
        if(vaild){
          formRules = vaild;
        }
      })
      if(!formRules){
        return;
      }else{
        if (this.formAdd.datas.clearRules==2 || this.formAdd.datas.clearRules>=4) {
          if (this.formAdd.dataDetails.length==0) {
            this.$message.warning("请填写明细信息！");
            return;
          }
          const formCellRules = this.$refs.dynamicCrud.$refs.crud.formCellRules;
          for(let index in this.formAdd.dataDetails){
            let result = await this.asyncValidator(formCellRules, this.formAdd.dataDetails[index])
              .then(() => {return null})
              .catch(errors => {return errors})
            if(result){
              this.$message.info(`第${++index}行：${result[0].message}`)
              return
            }
          }
        }
        addObj(this.formAdd)
          .then((data) => {
            this.$message.success("添加成功");
            this.getList(this.page);
            this.addVisableDialog = false;
            done();
          })
          .catch(() => {});
      }  
    },
    async detailEdit(){
      let formRules = false;
      this.$refs.editForm.validate(vaild=>{
        if(vaild){
          formRules = vaild;
        }
      })
      if(!formRules){
        return;
      }else{
        if (this.formEdit.datas.clearRules==2 || this.formEdit.datas.clearRules>=4) {
          if (this.formEdit.dataDetails.length==0) {
            this.$message.warning("请填写明细信息！");
            return;
          }
          const formCellRules = this.$refs.dynamicCrud.$refs.crud.formCellRules;
          for(let index in this.formEdit.dataDetails){
            let result = await this.asyncValidator(formCellRules, this.formEdit.dataDetails[index])
              .then(() => {return null})
              .catch(errors => {return errors})
            if(result){
              this.$message.info(`第${++index}行：${result[0].message}`)
              return
            }
          }
        }
        putObj(this.formEdit)
          .then((data) => {
            this.$message.success("修改成功");
            this.getList(this.page);
            this.editVisableDialog = false;
            done();
          })
          .catch(() => {});
      }  
    },
    //单边
    async OneSidedEdit(){
      let formRules = false;
      this.$refs.editForm.validate(vaild=>{
        if(vaild){
          formRules = vaild;
        }
      })
      if(!formRules){
        return;
      }else{
        if (this.formOneSided.cleanDate == null || this.formOneSided.cleanDate == "" || this.formOneSided.cleanDate == undefined) {
          this.$message.warning("请选择日期！");
          return;
        }
        if (this.formOneSided.dataOneSidedDetails.length==0) {
          this.$message.warning("请填写明细信息！");
          return;
        }
        updateOneSidedSales(this.formOneSided)
          .then((data) => {
            this.$message.success("编辑成功");
            this.getList(this.page);
            this.oneSidedVisableDialog = false;
            done();
          })
          .catch(() => {});
      }  
    },
    rowadd(callback){
      callback()
    },
    async submit (params, done) {
      const data = await autoComputeMonth(params);
      if (data) {
        this.$message.success('操作成功');
      } else {
        this.$message.error('操作失败，请联系管理员');
      }
      done()
      this.getList(this.page)
      this.dialogVisible = false
    },
    async submitDay (params, done) {
      const data = await autoComputeDay(params);
      if (data) {
        this.$message.success('操作成功');
      } else {
        this.$message.error('操作失败，请联系管理员');
      }
      done()
      this.getList(this.page)
      this.dialogVisible2 = false
    },
    getList (page, params) {
      this.tableLoading = true
      const [startDate, endDate] = this.searchForm.calcTime || [];
      fetchListB(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm, this.extraParam, { startDate, endDate })).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    async exportClick (row) {
      // await this.searchChange(row, () => { });
      this.dataExport();
    },
    async dataExport () {
      if (this.selection.length === 0) {
        this.$message.error('请选择要导出的数据');
        return;
      }
      let loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      })
      try {
        const res = await dataExport({ ids: this.selection });
        // handleExcelResponse(res, `${startDate}至${endDate}导出.xlsx`);
        handleExcelResponse(res);
      } finally {
        loading.close();
      }
    },
    async searchChange (form, done) {
      this.searchForm = { ...form };
      try {
        await this.getList(this.page, form);
      } finally {
        done();
      }
    },
    refreshChange () {
      this.getList(this.page)
    },
    selectionChange (list) {
      this.selection = list.map(l => l.id);
    },
    handleStart: function () {
      if (this.selection.length === 0) {
        this.$message.error('请选择要启动的规则');
        return;
      }
      updateUsedStateToUse(this.selection).then(data => {
        this.$message.success('启动成功')
        this.getList(this.page)
        done()
      }).catch(() => {
        loading();
      });
    },
    handleStop: function () {
      if (this.selection.length === 0) {
        this.$message.error('请选择要暂停的规则');
        return;
      }
      updateUsedStateToStop(this.selection).then(data => {
        this.$message.success('暂停成功')
        this.getList(this.page)
        done()
      }).catch(() => {
        loading();
      });
    },
    handleDelete: function () {
      if (this.selection.length === 0) {
        this.$message.error('请选择要删除的规则');
        return;
      }
      this.$confirm("是否需要删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success"
      }).then(() => {
        delObj({ids: this.selection,})
          .then(data => {
            if (data.data.code == "0") {
              this.$message.success("删除成功");
            }
            this.getList(this.page);
            done();
          })
          .catch(() => {
            loading();
          });
      });
    },
    searchReset () {
      this.page.currentPage = 1
      this.getList(this.page);
    },


    preivew (record) {
      this.current = record;
    },
    getPreviewList (page, params) {
      this.tablePreviewLoading = true
      const { current } = this
      previewLine(current.id).then(response => {
        this.tablePreviewData = response.data.data
        this.tablePreviewLoading = false
      }).catch(() => {
        this.tablePreviewLoading = false
      })
    },
  }
}
</script>
<style scoped>
  .bottom-menu-input {
    margin-top: 30px;
    text-align: center;
  }
</style>
